package by.demchenko.sample.webapp.page.admin;

import by.demchenko.sample.datamodel.Person;
import by.demchenko.sample.datamodel.Person_;
import by.demchenko.sample.datamodel.enums.UserType;
import by.demchenko.sample.services.PersonService;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import javax.inject.Inject;
import javax.persistence.metamodel.SingularAttribute;
import java.util.Iterator;

@AuthorizeInstantiation("ADMIN")
public class TeachersPage extends BaseAdminPage {

    @Inject
    PersonService personService;

    @Override
    protected void onInitialize() {
        super.onInitialize();
        add(new Label("headerTitle", getPageTitle()));

        PersonDataProvider personDataProvider = new PersonDataProvider();

        DataView<Person> dataView = new DataView<Person>("teachersList", personDataProvider, 3) {
            @Override
            protected void populateItem(Item<Person> item) {
                final Person teacher = item.getModelObject();
                item.add(new Label("firstName"));
                item.add(new Label("lastName"));
            }
        };

        add(dataView);

    }

    private class PersonDataProvider extends SortableDataProvider<Person, SingularAttribute<Person, ?>> {

        public PersonDataProvider() {
            super();
            setSort(Person_.lastName, SortOrder.ASCENDING);
        }

        @Override
        public Iterator<? extends Person> iterator(long l, long l1) {
            SingularAttribute<Person, ?> sortParam = getSort().getProperty();
            SortOrder propertySortOrder = getSortState().getPropertySortOrder(sortParam);
            boolean ascending = SortOrder.ASCENDING.equals(propertySortOrder);
            return personService.getPersonsByType(UserType.TEACHER, false).iterator();

        }

        @Override
        public long size() {
            return personService.getCount(UserType.TEACHER);
        }

        @Override
        public IModel<Person> model(Person teacher) {
            return new CompoundPropertyModel<>(teacher);
        }
    }

    private IModel<String> getPageTitle() {
        return new Model<String>(getClass().getSimpleName());
    }
}